#include "application_ex.h"
#include <QComboBox>
#include <QDateTime>
#include <QLineEdit>
#include <QDateEdit>
#include <QScreen>
#include <QDebug>

// add necessary includes here
#include "utils/keyboard/keyboard_mgr.h"


/*
 * Function:    ApplicationEx
 * Description: The constructor with params
 * Paramer:     int &argc
 *              char **argv
 * Return:
 */
ApplicationEx::ApplicationEx(int &argc, char **argv) :
    QApplication(argc, argv)
{
   qDebug() << Q_FUNC_INFO;

    Q_ASSERT(NULL != KeyboardMgr::getInstance(this));
}

/*
 * Function:    notify
 * Description: Override event filter
 * Paramer:     QObject *target - the target object
 *              QEvent *event - the event
 *              char **argv
 * Return:
 */
bool ApplicationEx::notify(QObject *target, QEvent *event)
{
    if("WidgetManagerWindow" == target->objectName() || "FormShieldDlg" == target->objectName() || "QQuickOffScreenWindow" == target->objectName()) {
        return QApplication::notify(target, event);
    }

    switch (event->type()) {
    case QEvent::MouseButtonPress:
        break;
    case QEvent::None:
        break;
    case QEvent::MouseButtonRelease:
    {
//        qDebug() << Q_FUNC_INFO << "MouseButtonRelease" << target->objectName() << KeyboardMgr::getInstance(this)->isVisible();

        // Exclude QDateEdit
        if("qt_spinbox_lineedit" == target->objectName()) break;

        QLineEdit *pEdit = qobject_cast<QLineEdit *>(target);
        if(pEdit){
            if(pEdit->isEnabled() && !pEdit->isReadOnly()) {
                // Coordinates relative to the window
//                QPoint pntEdit = pEdit->pos();

                // Coordinates relative to the screen
                QPoint pntEdit = pEdit->mapToGlobal(QPoint(0,0));

                KeyboardMgr::getInstance(this)->moveKeyboard(pntEdit.x(), pntEdit.y(), pEdit->width(), pEdit->height());

                KeyboardMgr::getInstance(this)->showKeyboard();
            }
            else {
                KeyboardMgr::getInstance(this)->hideKeyboard();
            }
        }
        else {
            if("" != target->objectName()
                    && "VirtualKeyboard" != target->objectName()
                    && "keyboardInputArea" != target->objectName()
                    && "wordCandidateView" != target->objectName()) {
                KeyboardMgr::getInstance(this)->hideKeyboard();
            }
        }

        break;
    }
    default:
        break;
    }

    return QApplication::notify(target, event);
}
